package cn.lixufeng.user.service.impl;

import cn.lixufeng.basic.exception.BusinessException;
import cn.lixufeng.basic.utils.AjaxResult;
import cn.lixufeng.basic.utils.HttpClientUtils;
import cn.lixufeng.basic.utils.MD5Utils;
import cn.lixufeng.basic.utils.StrUtils;
import cn.lixufeng.user.constant.UserConstants;
import cn.lixufeng.user.domain.LoginInfo;
import cn.lixufeng.user.domain.User;
import cn.lixufeng.user.domain.WxUser;
import cn.lixufeng.user.dto.LoginDto;
import cn.lixufeng.user.mapper.LoginInfoMapper;
import cn.lixufeng.user.mapper.UserMapper;
import cn.lixufeng.user.mapper.WxUserMapper;
import cn.lixufeng.user.service.ILoginService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 账号登录
     * @param loginDto
     * @return
     */
    @Override
    public Map<String,Object> accountLogin(LoginDto loginDto) {
        // 校验参数不能为空
        if(StringUtils.isEmpty(loginDto.getUsername())
                || StringUtils.isEmpty(loginDto.getPassword())
                || StringUtils.isEmpty(loginDto.getType())){
            throw new BusinessException("请填写完整登录信息！");
        }
        // 查询登录数据username和type
        LoginInfo loginInfo = loginInfoMapper.findByLoginDto(loginDto);
        // 如果没查到
        if(loginInfo == null){
            throw new BusinessException("用户名或密码错误！");
        }
        // 如果查到了，校验密码，最终的密码要有盐值和md5加密后的密码
        String salt = loginInfo.getSalt();
        String md5Password = loginInfo.getPassword();
        String password = loginDto.getPassword();
        // 如果密码错误
        if(!md5Password.equals(MD5Utils.encrypByMd5(password+salt))){
            // 模糊地告诉用户有错，不能说太明白，防止猜密码
            throw new BusinessException("用户名或密码错误！");
        }
        // 如果密码正确，登录成功，需要保存redis还有token
        String token = UUID.randomUUID().toString();// toString转换成字符串
        redisTemplate.opsForValue().set(token,loginInfo,30,TimeUnit.MINUTES);
        // 用map存放token和LoginInfo
        Map<String,Object> map = new HashMap<>();
        map.put("token", token);
        // 为了保护隐私信息如盐值和密码等不让网页能看到这些，需要置空这些参数
        loginInfo.setSalt(null);
        loginInfo.setPassword(null);
        map.put("loginInfo", loginInfo);
        return map;
    }

    /**
     * 微信登录
     * @param params
     * @return
     */
    @Override
    public AjaxResult wechat(Map<String, String> params) {
        // 获取code授权码
        String code = params.get("code");
        // 如果没有
        if(!StringUtils.hasLength(code)){
            throw new BusinessException("没有授权码！");
        }
        // 获取微信的token令牌
        String getTokenUrl = UserConstants.WXUSER_GET_TOKEN_URL
                .replace("APPID", UserConstants.APPID)
                .replace("SECRET", UserConstants.SECRET)
                .replace("CODE", code);

        // 通过code授权码获取微信的token令牌
        String tokenObjStr = HttpClientUtils.httpGet(getTokenUrl);
        JSONObject jsonObject = JSONObject.parseObject(tokenObjStr);
        String accessToken = jsonObject.getString("access_token");//令牌
        String openId = jsonObject.getString("openid");//微信号
        //2.根据openId 查询t_wxuser
        WxUser wxUser = wxUserMapper.findByOpenId(openId);
        //3.判断微信用户是否已经在我们平台绑定过
        if(wxUser != null && wxUser.getUser_id() != null){
            // 直接扫码登录  免密登录
            LoginInfo loginInfo = loginInfoMapper.findByUserId(wxUser.getUser_id());
            // 登录成功，保存redis和token
            String token = UUID.randomUUID().toString();//514dc79b-2b9f-48be-88a8-1b012dee80ab
            redisTemplate.opsForValue().set(
                    token,
                    loginInfo,
                    30,
                    TimeUnit.MINUTES);// 30min过期
            // 返回token + loginInfo
            Map<String,Object> map = new HashMap<>();
            map.put("token", token);
            // 把敏感信息置空
            loginInfo.setSalt(null);
            loginInfo.setPassword(null);
            map.put("loginInfo", loginInfo);
            return AjaxResult.me().setResultObj(map);
        }
        // 找不到用户第一次扫码，前端跳转到绑定页面,并携带token和openId回去
        String binderUrlParams = "?accessToken="+accessToken+"&openId="+openId;
        return AjaxResult.me().setSuccess(false).setResultObj(binderUrlParams);
    }

    @Override
    public Map<String, Object> binder(Map<String, String> params) {
        // 校验
        String phone = params.get("phone");
        String verifyCode = params.get("verifyCode");
        String accessToken = params.get("accessToken");
        String openId = params.get("openId");
        if(!StringUtils.hasLength(phone)
                || !StringUtils.hasLength(verifyCode)
                || !StringUtils.hasLength(accessToken)
                || !StringUtils.hasLength(openId)){
            throw new BusinessException("必要信息为空！");
        }
        // 验证是否过期
        Object codeTmp = redisTemplate.opsForValue().get(UserConstants.BUSINESS_BINDER_PREFIX + phone);
        if(codeTmp == null){
            throw new BusinessException("验证码已过期，请重新获取！");
        }
        // 校验验证码是否相等且不分大小写equalsIgnoreCase
        String code = codeTmp.toString().split(":")[0];
        if(!verifyCode.equalsIgnoreCase(code)){
            throw new BusinessException("验证码错误！");
        }
        // 手机不能注册
        User userTmp = userMapper.findByPhone(phone);
        User user = null;
        LoginInfo loginInfo = null;
        if(userTmp != null){// 已经注册过了，直接绑定微信用户
            // 没有微信用户，先等等
            user = userTmp;
            loginInfo = loginInfoMapper.findById(user.getLogininfo_id());
        }else{// 如果没有用户，创建平台用户
            user = initUser(phone);
            loginInfo = user2LoginInfo(user);
            loginInfoMapper.add(loginInfo);
            user.setLogininfo_id(loginInfo.getId());
            userMapper.add(user);
        }
        // 通过token和openId来获取微信用户信息
        String getUserUrl = UserConstants.WXUSER_GET_USER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserTmp = HttpClientUtils.httpGet(getUserUrl);
        // 生成wxuser信息并绑定平台用户
        WxUser wxUser = initWxUser(wxUserTmp,user);
        wxUserMapper.add(wxUser);


        // 免密登录 直接扫码登录 登录成功 保存redis和token
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                loginInfo,
                30,
                TimeUnit.MINUTES);
        // 返回token和logiInfo
        Map<String,Object> map = new HashMap<>();
        map.put("token", token);
        // 把敏感信息置空
        loginInfo.setSalt(null);
        loginInfo.setPassword(null);
        map.put("loginInfo", loginInfo);
        return map;
    }

    private WxUser initWxUser(String wxUserTmp, User user) {
        // 装换微信用户信息
        JSONObject jsonObject = JSONObject.parseObject(wxUserTmp);
        WxUser wxUser =  new WxUser();
        wxUser.setUser_id(user.getId());//绑定用户
        wxUser.setOpenid(jsonObject.getString("openid"));
        wxUser.setNickname(jsonObject.getString("nickname"));
        wxUser.setSex(jsonObject.getInteger("sex"));
        wxUser.setAddress(null);
        wxUser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxUser.setUnionid(jsonObject.getString("unionid"));
        return wxUser;
    }

    private LoginInfo user2LoginInfo(User user) {
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(user, loginInfo);
        loginInfo.setType(1);
        return loginInfo;
    }

    private User initUser(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        // 使用盐值加密md5加密之后的密码 生成随机密码并发短信通知用户
        String md5Pwd = MD5Utils.encrypByMd5("1" + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }
}
